/**
 *    Copyright ${license.git.copyrightYears} the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.mapping;

import java.util.Collections;
import java.util.Map;

import org.apache.ibatis.session.Configuration;

/**
 * @author Clinton Begin
 * 每个鉴别器节点都表示为一个Discriminator
 *
 * 用法:
 *    <resultMap id="BaseResult" type="com.lc.model.XTest">
 *         <result column="id" jdbcType="INTEGER" property="id"/>
 *         <result column="name" jdbcType="VARCHAR"  property="name"/>
 *         <result column="age" jdbcType="INTEGER" property="age"/>
 *         <result column="money" jdbcType="DOUBLE" property="money"/>
 *         <result column="type" jdbcType="CHAR" property="type"/>
 *         <!-- 鉴别器允许至多一个 -->
 *         <discriminator javaType="char" column="type">
 *             <case value="A" resultType="com.lc.model.ATest">
 *                 <result column="type" property="t" />
 *             </case>
 *             <case value="B" resultType="com.lc.model.BTest">
 *                 <result column="type" property="t" />
 *             </case>
 *         </discriminator>
`*     </resultMap>
 */
public class Discriminator {
  // 所属的属性节点<result>
  private ResultMapping resultMapping;
  // 内部的if then映射
  private Map<String, String> discriminatorMap;

  Discriminator() {
  }

  public static class Builder {
    private Discriminator discriminator = new Discriminator();

    public Builder(Configuration configuration, ResultMapping resultMapping, Map<String, String> discriminatorMap) {
      discriminator.resultMapping = resultMapping;
      discriminator.discriminatorMap = discriminatorMap;
    }

    public Discriminator build() {
      assert discriminator.resultMapping != null;
      assert discriminator.discriminatorMap != null;
      assert !discriminator.discriminatorMap.isEmpty();
      //lock down map
      discriminator.discriminatorMap = Collections.unmodifiableMap(discriminator.discriminatorMap);
      return discriminator;
    }
  }

  public ResultMapping getResultMapping() {
    return resultMapping;
  }

  public Map<String, String> getDiscriminatorMap() {
    return discriminatorMap;
  }

  public String getMapIdFor(String s) {
    return discriminatorMap.get(s);
  }

}
